package org.tio.sitexxx.web.server.controller.minip;


import com.alibaba.fastjson.JSON;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Record;
import net.sf.json.JSONObject;
import org.tio.http.common.HttpRequest;
import org.tio.http.server.annotation.RequestPath;
import org.tio.sitexxx.service.model.main.Consultant;
import org.tio.sitexxx.service.model.main.Member;
import org.tio.sitexxx.service.model.main.Promoter;
import org.tio.sitexxx.service.model.main.Promotion;
import org.tio.sitexxx.service.service.qj.ConsultantService;
import org.tio.sitexxx.service.service.qj.MemberService;
import org.tio.sitexxx.service.service.qj.PromoterService;
import org.tio.sitexxx.service.service.qj.PromotionService;
import org.tio.sitexxx.service.vo.Const;
import org.tio.sitexxx.web.server.utils.WxConsultantLogin;
import org.tio.sitexxx.web.server.utils.Wxlogin;

import java.sql.SQLException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RequestPath(value = "/users/consultant")
public class user_c_controller {
    public static final String db = Const.Db.TIO_SITE_MAIN;
    public user_c_controller(){

    }

    /**
     * 顾问登陆
     * @param request
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    @RequestPath(value = "/mplogin")
    public Object mplogin(HttpRequest request) throws Exception {
        Map<String, Object> requestmap = JSON.parseObject(request.getBodyString());
        Map<String, Object> resultMap = new HashMap<String, Object>();


        JSONObject SessionKeyOpenId = WxConsultantLogin.getSessionKeyOrOpenId((String) requestmap.get("code"));

        System.out.println("code:"+requestmap.get("code"));
        if (SessionKeyOpenId.get("errcode") != null) {
            resultMap.put("openid", "fail");
            return resultMap;
        }
        String openid = SessionKeyOpenId.getString("openid");
        String sessionKey = SessionKeyOpenId.getString("session_key");

        Consultant consultant= ConsultantService.me.getConsultantByOpenId(openid);
        Map<String, Object> newconsultant = new HashMap<>(12);//新注册返回的json
        Map<String, Object> oldconsultant = new HashMap<>(12);//曾注册返回的json
        System.out.println("openid:"+openid);
        //用户未登陆过
        if (consultant == null) {
            Date date = new Date();
            JSONObject userInfo = Wxlogin.getUserInfo((String) requestmap.get("encryptedData"), sessionKey, (String) requestmap.get("iv"));
            String avatar=userInfo.getString("avatarUrl");
            String gender=userInfo.getString("gender");
            String nickname=userInfo.getString("nickName");
            System.out.println("gender:" + userInfo.getString("gender"));
            Db.tx(new IAtom() {
                @Override
                public boolean run() throws SQLException {
//                    Db.use(db).save("member", "id", member);
                    Record consultant=new Record().set("avata",avatar).set("name",nickname)
                            .set("gender",gender).set("works3","gg.jpg").set("createdAt",date).set("updatedAt",date).set("openid",openid);
                    Db.use(db).save("consultant","id",consultant);
                    Record user=new Record().set("id",consultant.get("id")).set("loginname",openid).set("nick",nickname)
                            .set("status",1).set("createtime",date).set("updatetime",date).set("avatar",avatar)
                            .set("pwd","").set("ipid",0);
                    Db.use(db).save("user", user);
                    System.out.println("nickname:"+nickname);
                    Record consultant_staff=new Record().set("id",consultant.get("id")).set("avata",avatar)
                            .set("name",nickname).set("openid",openid).set("flag",1);
                    Db.use(db).save("consultant_service_staff",consultant_staff);
                    return true;
                }
            });
            Consultant consultant1= ConsultantService.me.getConsultantByOpenId(openid);//返回刚注册的用户
            newconsultant=JSON.parseObject(JSON.toJSONString(consultant1),Map.class);
            newconsultant.put("isFirst",true);//第一次注册，肯定未审核
            return newconsultant;
        }else if(consultant.getAudit()==null){//未被审核
            oldconsultant=JSON.parseObject(JSON.toJSONString(consultant),Map.class);
            oldconsultant.put("IsAudit",-1);
        }else if(!consultant.getAudit()){//审核不通过
            oldconsultant=JSON.parseObject(JSON.toJSONString(consultant),Map.class);
            oldconsultant.put("IsAudit",-2);
        }else{
            oldconsultant=JSON.parseObject(JSON.toJSONString(consultant),Map.class);
            oldconsultant.put("IsAudit",0);//审核通过
        }
        Integer balance=(Integer) oldconsultant.get("balance");
        if(null!=balance)oldconsultant.put("balance",(float)balance/100);
        return oldconsultant;//曾登陆顾问
    }
}
